#!/usr/bin/perl
use CGI qw(:standard);
use DBI;
use JSON;


my $cgi = new CGI;
my $num_chauf = $cgi->param('num_chauf') ;
$num_chauf = 0 if (not defined($num_chauf));
my $interval = $cgi->param('interval') ;
$interval = 1 if (not defined($interval));

print $cgi->header('application/json');

my @chauffage ;
#parse_config();

my $dsn = "dbi:mysql:mamaison:127.0.0.1:3306";
my $dbh = DBI->connect($dsn, 'root', '');

my $query = "select date,TRUNCATE(avg(c".$num_chauf."target),2),TRUNCATE(avg(c".$num_chauf."curtemp),2) from log where date >= date(DATE_SUB(now(), INTERVAL 1 DAY)) group by unix_timestamp(date) div ".$interval."  order by date";
my $sth   = $dbh->prepare($query);
$sth->execute();
my @table1;
my @table2;

while (my ($date,$cur1,$cur2) = $sth->fetchrow) 
	{
    $cur1 = 0 if (not defined $cur1);
    $cur2 = 0 if (not defined $cur2);
#    push(@table1, [$date,int($cur1*100)/100]);
#    push(@table2, [$date,int($cur2*100)/100]);
    push(@table1, [$date,$cur1]);
    push(@table2, [$date,$cur2]);
}
my $json;
$json->{'line1'} = \@table1 ;
$json->{'line2'} = \@table2 ;
$json->{'num_chauf'} = $num_chauf;
my $json_text = to_json($json);
print $json_text;

